package com.odl.ds.utils;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载
 *
 * @author Antoneo
 * @create 2018-10-08 14:51
 **/
@Slf4j
public class DownLoadUtils {
    public static void  downLoadByUrl(String urlStr,String fileName,String savePath) throws Exception{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        File file=saveFile(fileName,savePath,readInputStream(inputStream));
        if(inputStream!=null){
            inputStream.close();
        }
        log.info("信息:"+url+" 下载成功！保存路径:"+file.getPath());
    }


    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static File saveFile(String fileName,String savePath,byte[] bytes) throws Exception {
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            FileUtils.mkDir(savePath);
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);
        if(fos!=null){
            fos.close();
        }
        return file;
    }

    /**
     * 下载SVG
     * @param url
     * @param fileName
     * @param savePath
     * @throws Exception
     */
    public static void downloadSvg(String url,String fileName,String savePath) throws Exception{
        // 使用Jsoup建立连接
        Connection.Response response = Jsoup.connect(url)
                .ignoreContentType(true)  // 必须设置为true才能下载非HTML内容
                .execute();
        // 检查状态码
        int statusCode = response.statusCode();
        if (statusCode != 200) {
            log.info("服务器返回HTTP响应码: " + statusCode);
        }

        // 检查内容类型
        String contentType = response.contentType();
        if (contentType != null && !contentType.equals("image/svg+xml")) {
            log.info("下载的文件可能不是SVG格式 (Content-Type: " + contentType + ")");
        }
        // 获取字节数据并写入文件
        byte[] fileData = response.bodyAsBytes();

        File file=saveFile(fileName,savePath,fileData);

        log.info("信息:"+url+" 下载成功！保存路径:"+file.getPath());
    }


    public static void main(String[] args) {
        try{
            downLoadByUrl("https://cdn.undraw.co/illustration/stripe-payments_jxnn.svg",
                    "1.svg","E:\\UI库");
        }catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}

